package com.becca.cake.core.socket;

import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;

import java.net.MalformedURLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.JSONObject;

import com.alibaba.fastjson.JSON;
import com.becca.cake.core.constant.CommonConstants;

/**
 * scoket推送
 * @author hejinguo
 * @version $Id: SocketMessage.java, v 0.1 2013-1-9 上午10:34:20
 */
public class SocketMessage implements IOCallback {
    protected Log                logger        = LogFactory.getLog(getClass());
    private static SocketMessage socketMessage = null;
    private SocketIO             socket        = null;

    public SocketMessage() {
        try {
            socket = new SocketIO();
            socket.connect(CommonConstants.NODE_SOCKET_URL, this);
        } catch (MalformedURLException e) {
            logger.error("socket连接错误,请检查推送地址是否开启!", e);
        } catch (Exception e) {
            logger.error("socket连接时产生错误!", e);
        }
    }

    @Override
    public void onMessage(JSONObject json, IOAcknowledge ack) {
        try {
            if (logger.isInfoEnabled()) {
                logger.info("服务器方的Josn消息为:" + json.toString(2));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onMessage(String data, IOAcknowledge ack) {
        if (logger.isInfoEnabled()) {
            logger.info("服务器发送的消息为:" + data);
        }
    }

    @Override
    public void onError(SocketIOException socketIOException) {
        if (logger.isErrorEnabled()) {
            logger.error("SocketIO发生错误!错误信息:" + socketIOException.getMessage());
            socketIOException.printStackTrace();
        }
    }

    @Override
    public void onDisconnect() {
        if (logger.isInfoEnabled()) {
            logger.info("Socket连接已断开!");
        }
    }

    @Override
    public void onConnect() {
        if (logger.isInfoEnabled()) {
            logger.info("Socket已成功连接!");
        }
    }

    @Override
    public void on(String event, IOAcknowledge ack, Object... args) {
        if (logger.isInfoEnabled()) {
            logger.info("服务器调用推送消息时间名称:" + event);
        }
    }

    /**
     * 单例
     * @return
     */
    public static SocketMessage getInstance() {
        if (socketMessage == null) {
            socketMessage = new SocketMessage();
        }
        return socketMessage;
    }

    /**
     * 推送消息
     */
    public void sendMassge(String meaasge) {
        socket.emit("send", JSON.parse(meaasge));
    }

    /**
     *已确认订单信息推送
     */
    public void sendOrderConCountMessage(String meaasge) {
        socket.emit("ordercount", JSON.parse(meaasge));
    }

}
